﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Devices.PointOfService;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace WellDone
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 

    public sealed partial class USAePayDialog : Page
    {
        public event EventHandler CloseRequested;
        private DispatcherTimer timer; 
        private int curr_cnt=0, last_cnt=0;
        public decimal amount = 0;
        public int invoiceNo = 0, ordernumber=0;
        public string strAuthCode = "";
            
        public USAePayDialog()
        {
            this.InitializeComponent();
        }

        public void focusCapture()
        {
            tbCapture.Focus(Windows.UI.Xaml.FocusState.Programmatic);
            timer = new DispatcherTimer();
            timer.Tick += timer_Tick;
            timer.Interval = TimeSpan.FromSeconds(0.2);
            timer.Start();
        }

        private async void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (Globals.strExceptionMessage.Length > 0)
            {
                // Log error...
                await Globals.client.AppendToLogAsync(Globals.token, Globals.strExceptionMessage);
                Globals.strExceptionMessage = "";
            }
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
            System.Diagnostics.Debug.WriteLine(tbCapture.Text);
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }

        private async void timer_Tick(object sender, object e)
        {
            if (tbCapture.Text.Length > 0)
            {
                if (tbMessage.Text.ToLower().Contains("swipe"))
                {
                    tbMessage.Text = "Reading Card Data...";
                    btnCancel.Visibility = Visibility.Collapsed;
                }
                last_cnt = curr_cnt;
                curr_cnt = tbCapture.Text.Length;
                if (curr_cnt == last_cnt)
                {
                    tbMessage.Text = "Authorizing...";
                    timer.Stop();
                    try
                    {
                        ServiceReferenceUSAePay.PaymentRequest request = new ServiceReferenceUSAePay.PaymentRequest();
                        request.Amount = amount;
                        request.SourceKey = Globals.strUSAePaySourceKey;
                        request.Pin = Globals.strUSAePayPin;
                        request.MagStripeData = tbCapture.Text;
                        request.InvoiceNo = invoiceNo;
                        ServiceReferenceUSAePay.PaymentResponse response = await Globals.usaepayClient.ProcessPreAuthAsync(request);
                        // Parse card # and customer name
                        string strPartialCardNum = tbCapture.Text.Substring(22, 4) + tbCapture.Text.Substring(34, 4);
                        string strCustLastName = tbCapture.Text.Substring(39, tbCapture.Text.IndexOf("/")-39);
                        string strCustFirstMIName = tbCapture.Text.Substring(tbCapture.Text.IndexOf("/") + 1, tbCapture.Text.LastIndexOf("^") - tbCapture.Text.IndexOf("/") - 1).Trim();
                        // If the transaction is authorized, update the database...
                        if (response.ResultCode == "A")
                        {
                            ServiceReferenceOpenRPOS.USAePay usaepay_rec = new ServiceReferenceOpenRPOS.USAePay();
                            usaepay_rec.bFilterAuthCode = true;
                            usaepay_rec.bFilterAuthorized = true;
                            usaepay_rec.bFilterCustomerFMName = true;
                            usaepay_rec.bFilterCustomerLastName = true;
                            usaepay_rec.bFilterOrderCheckID = true;
                            usaepay_rec.bFilterPartialCardNumber = true;
                            usaepay_rec.bFilterPosted = true;
                            usaepay_rec.bFilterRefNum = true;
                            usaepay_rec.col_AuthCode = response.AuthCode;
                            usaepay_rec.col_Authorized = true;
                            usaepay_rec.col_CustomerFMName = strCustFirstMIName;
                            usaepay_rec.col_CustomerLastName = strCustLastName;
                            usaepay_rec.col_OrderCheckID = invoiceNo;
                            usaepay_rec.col_PartialCardNumber = strPartialCardNum;
                            usaepay_rec.col_Posted = false;
                            usaepay_rec.col_RefNum = response.RefNum;
                            await Globals.client.AddUSAePayObjectAsync(Globals.token, usaepay_rec);
                            // Update the order check...
                            ServiceReferenceOpenRPOS.OrderCheck oc = new ServiceReferenceOpenRPOS.OrderCheck();
                            oc.col_ID = invoiceNo;
                            oc.bFilterAuthCode = true;
                            oc.col_AuthCode = response.AuthCode;
                            await Globals.client.UpdateOrderCheckObjectAsync(Globals.token, oc);
                            strAuthCode = response.AuthCode;
                            // Print the credit slip...
                            ServiceReferenceOpenRPOS.PrintQueue pq = new ServiceReferenceOpenRPOS.PrintQueue();
                            pq.bFilterCreditSlip = true;
                            pq.col_CreditSlip = true;
                            pq.bFilterOrderSummaryID = true;
                            pq.col_OrderSummaryID = ordernumber;
                            pq.bFilterPrinted = true;
                            pq.col_Printed = false;
                            pq.bFilterOrderCheckID = true;
                            pq.col_OrderCheckID = invoiceNo;
                            pq.bFilterPrintRoute = true;
                            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                            Object value = localSettings.Values[Globals.k_str_settings_receipt_print_route];
                            try
                            {
                                pq.col_PrintRoute = Convert.ToByte(value);
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine(ex.Message);
                            }
                            try
                            {
                                // Only print credit slips if above threshold...
                                if (request.Amount > (decimal)Globals.credit_threshold)
                                {
                                    // Print 2X credit slips...
                                    await Globals.client.AddPrintQueueObjectAsync(Globals.token, pq);
                                    await Globals.client.AddPrintQueueObjectAsync(Globals.token, pq);
                                }
                                pq.bFilterPrintReceipt = true;
                                pq.col_PrintReceipt = true;
                                pq.col_CreditSlip = false;
                                await Globals.client.AddPrintQueueObjectAsync(Globals.token, pq);
                            }
                            catch (Exception ex)
                            {
                                Globals.strExceptionMessage = "usaepay Exception: " + ex.Message;
                                System.Diagnostics.Debug.WriteLine(ex.Message);
                            }

                        }
                        // Display the result...
                        tbMessage.Text = response.Result;
                    }
                    catch (Exception ex)
                    {
                        tbMessage.Text = "Error Processing Card.";
                        Globals.strExceptionMessage = "usaepay (outer) Exception: " + ex.Message;
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                    finally
                    {
                        btnClose.Visibility = Visibility.Visible;
                    }
                }
            }
        } 


    }
}
